
import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { View, Text, StyleSheet, ScrollView, Image, TouchableOpacity, Dimensions, Animated, Easing, StatusBar, Platform } from 'react-native';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Icon from 'react-native-vector-icons/Ionicons';
import { locationAPI } from '../api';
import voiceService from '../services/voiceService';
import trackPlayerService from '../services/trackPlayerService';
import baiduTtsService from '../services/baiduTtsService';
import AsyncStorage from '@react-native-async-storage/async-storage';
import RNFS from 'react-native-fs';
import Sound from 'react-native-sound';
import { COLORS, RADIUS, FONT_SIZE, FONT_WEIGHT, SPACING } from '../styles/constants';
import { useAudioPlayer } from '../context/AudioPlayerContext';

const { width, height } = Dimensions.get('window');
const screenData = Dimensions.get('screen');
const realHeight = screenData.height; // 获取真实屏幕高度，包括系统UI

// 辅助函数：验证图片 URI 是否有效
const isValidImageUri = uri => {
  return uri && uri !== 'null' && uri !== '' && typeof uri === 'string';
};

// 辅助函数：获取有效的图片 URI，返回 null 或有效 URI
const getValidImageUri = (primary, fallback) => {
  if (isValidImageUri(primary)) return primary;
  if (isValidImageUri(fallback)) return fallback;
  return null;
};

const DEFAULT_TAB_BAR_STYLE = {
  backgroundColor: COLORS.white,
  borderTopWidth: 1,
  borderTopColor: COLORS.border.medium,
  paddingBottom: Platform.OS === 'ios' ? SPACING.xl : SPACING.sm,
  paddingTop: 5,
  height: Platform.OS === 'ios' ? 85 : 60,
};

// 常量配置
const CONSTANTS = {
  PROGRESS_BAR_WIDTH: 200,
  ROTATION_DURATION: 8000, // 旋转动画持续时间
  PROGRESS_UPDATE_INTERVAL: 1000, // 进度更新间隔
  FAST_SEEK_DURATION: 15, // 快进快退秒数
};

export default function AttractionDetailScreen({ route }) {
  const { attraction, itemType: _itemType, itemId, areaType } = route.params;
  const navigation = useNavigation();
  const insets = useSafeAreaInsets();

  // 使用全局音频播放器 Context
  const audioPlayerContext = useAudioPlayer();
  const [isPlaying, setIsPlaying] = useState(false);
  const [_isBuffering, setIsBuffering] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [audioUrl, setAudioUrl] = useState(null);
  const [audioText, setAudioText] = useState(null);
  const [currentTitle, setCurrentTitle] = useState(''); // 当前播放内容的标题
  const [showLyrics, setShowLyrics] = useState(false); // 控制显示歌词还是封面
  const [contentList, setContentList] = useState([]); // 存储所有内容列表
  const [currentContentIndex, setCurrentContentIndex] = useState(0); // 当前播放的内容索引
  const [spotsList, setSpotsList] = useState([]); // 景区下的景点列表
  const [loadingSpots, setLoadingSpots] = useState(false); // 加载景点列表状态
  const [scenicInfo, setScenicInfo] = useState(null); // 景区详细信息
  const [isTtsGenerating, setIsTtsGenerating] = useState(false); // TTS生成状态
  const autoPlayRef = useRef(true);
  const ttsSoundRef = useRef(null); // TTS音频对象
  const nextContentPreloadRef = useRef(null); // 下一个内容的预加载数据
  const isAutoSwitchingRef = useRef(false); // 标记是否正在自动切换

  // Refs
  const scrollY = useRef(new Animated.Value(0)).current;
  const rotateValue = useRef(new Animated.Value(0)).current;
  const spinAnimationRef = useRef(null); // 旋转动画引用
  const lyricsScrollRef = useRef(null); // 歌词滚动引用
  const _scrollAnimationRef = useRef(null); // 滚动动画引用
  const buttonPressedRef = useRef(false); // 标记是否点击了播放按钮
  const progressIntervalRef = useRef(null);
  const _hasLoadedInitialData = useRef(false);
  const lastPlayedAudioUrlRef = useRef(null); // 记录最后播放的音频URL
  const lastFetchedItemIdRef = useRef(null); // 记录最后获取数据的景区ID
  const isRestoringAudioRef = useRef(false); // 标记是否正在恢复音频

  useEffect(() => {
    const setup = async () => {
      const val = await AsyncStorage.getItem('auto_voice_play_enabled');
      autoPlayRef.current = val !== 'false';
      voiceService.initialize();

      // 设置导航引用，让全局控制条可以返回详情页
      audioPlayerContext.setNavigation(navigation);
    };
    setup();
    return () => {
      // 离开页面时不自动停止播放，由用户通过全局控制条控制
      // voiceService.stopAudio(); // 注释掉自动停止
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
        progressIntervalRef.current = null;
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [navigation]);

  // 手势返回功能（暂时禁用以避免事件绑定错误）
  const panResponder = useRef(null);

  // 隐藏导航栏和强制全屏 - 只在当前页面生效
  useFocusEffect(
    useCallback(() => {
      const parentNavigator = navigation.getParent();

      parentNavigator?.setOptions({
        tabBarStyle: {
          ...DEFAULT_TAB_BAR_STYLE,
          display: 'none',
        },
      });

      navigation.setOptions({
        headerShown: false,
        statusBarStyle: 'light',
        statusBarBackgroundColor: 'transparent',
        statusBarTranslucent: true,
        statusBarHidden: true,
        navigationBarHidden: Platform.OS === 'android',
        fullScreen: Platform.OS === 'android',
      });

      StatusBar.setBarStyle('light-content');
      StatusBar.setHidden(true, 'fade');

      // 进入页面时，重置 fetchAudioData 防护标志
      lastFetchedItemIdRef.current = null;

      // 进入页面时，检查是否是当前正在播放的景区
      const currentAttractionId = audioPlayerContext.currentAttraction?.id;
      const isCurrentlyPlaying = audioPlayerContext.isPlaying;

      if (currentAttractionId === itemId) {
        // 如果是当前播放的景区，同步播放状态
        setIsPlaying(isCurrentlyPlaying);
      } else if (currentAttractionId && (isCurrentlyPlaying || audioPlayerContext.isPaused)) {
        // ⚡⚡⚡ 关键修复：如果有其他景区正在播放或暂停，完全停止它
        
        // 在内部执行异步操作
        (async () => {
          // 1. 停止TTS音频
          if (ttsSoundRef.current) {
            try {
              ttsSoundRef.current.stop();
              ttsSoundRef.current.release();
            } catch (e) {
            }
            ttsSoundRef.current = null;
          }
          
          // 2. 停止流式TTS
          try {
            await baiduTtsService.stop();
          } catch (e) {
          }
          
          // 3. 停止普通音频（TrackPlayer）
          try {
            await voiceService.stopAudio();
          } catch (e) {
          }
          
          // 4. 确保 TrackPlayer 完全停止
          try {
            await trackPlayerService.stop();
          } catch (e) {
          }
          
          // 5. 清除全局状态
          audioPlayerContext.stop();
          
          // 6. 清除本地状态
          setIsPlaying(false);
          setCurrentTime(0);
          setDuration(0);
          
        })();
      }

      // 离开页面时恢复导航栏
      return () => {
        parentNavigator?.setOptions({
          tabBarStyle: DEFAULT_TAB_BAR_STYLE,
        });

        navigation.setOptions({
          headerShown: false,
          statusBarStyle: 'dark',
          statusBarHidden: false,
          navigationBarHidden: false,
          fullScreen: false,
        });

        StatusBar.setHidden(false, 'fade');
        StatusBar.setBarStyle('dark-content');
      };
    }, [navigation, itemId]),
  );

  // 模拟音频数据 - 使用useMemo缓存
  const _audioData = useMemo(
    () => ({
      title: `${attraction.name} - 景点介绍`,
      author: '旅游向导',
      description: `欢迎来到${attraction.name}！这里是${attraction.address}，拥有悠久的历史和丰富的文化内涵。让我们一起探索这个美丽的景点，了解它的故事和魅力。`,
    }),
    [attraction.name, attraction.address],
  );

  // 获取音频数据
  useEffect(() => {
    const fetchAudioData = async () => {
      // 防止重复调用
      if (isRestoringAudioRef.current) {
        return;
      }

      if (lastFetchedItemIdRef.current === itemId) {
        return;
      }

      lastFetchedItemIdRef.current = itemId;

      try {
        let response;

        // 根据 areaType 判断调用哪个接口
        if (areaType === 1) {
          response = await locationAPI.getScenicAudioAndText(itemId);
        } else if (areaType === 2) {
          response = await locationAPI.getScenicSpotAudioAndText(itemId);
        } else {
          return;
        }

        const audioData = response?.data?.data || response?.data;

        if (audioData) {
          const list = audioData.contentList || [];
          setContentList(list); // 保存完整的内容列表

          if (list.length > 0) {
            const firstContent = list[0];
            const url =
              firstContent.audioUrl || firstContent.audio || firstContent.url;
            const text =
              firstContent.text ||
              firstContent.description ||
              firstContent.content;
            const title = firstContent.title || firstContent.name || `第 1 段`;

            // ⭐ 关键判断：如果有文字但没有音频URL，使用TTS
            if (!url && text) {
              setAudioText(text);
              setCurrentTitle(title);
              setCurrentContentIndex(0);
              setIsPlaying(false);
              setDuration(0);
              setCurrentTime(0);
              generateTtsAudio(text);
              return;
            }

            // 检查是否是同一个景区
            const isSameAttraction =
              audioPlayerContext.currentAttraction?.id === itemId;
            const isSameUrl =
              audioPlayerContext.currentAttraction?.audioUrl === url;


            // ⭐ 如果是同一个景区且同一个 URL，同步状态但不重新加载音频
            if (isSameAttraction && isSameUrl) {

              // ⭐⭐⭐ 始终设置页面数据，确保页面有内容显示
              setAudioText(text);
              setCurrentTitle(title);
              setCurrentContentIndex(0);
              setContentList(list); // 确保内容列表也被设置

              const hasAudioObject = voiceService.currentSound !== null;
              const shouldBePlaying =
                audioPlayerContext.isPlaying || audioPlayerContext.isPaused;

              // ⭐⭐⭐ 重要修复：如果当前 audioUrl 是空的，必须设置它，否则会触发停止逻辑
              if (!audioUrl) {
                setAudioUrl(url);
                setDuration(firstContent.duration || 0);
                setCurrentTime(audioPlayerContext.currentTime || 0); // 也要恢复播放位置
              } else {
                // audioUrl 已有值，只需要同步时长和位置
                setDuration(
                  firstContent.duration || audioPlayerContext.duration || 0,
                );
                setCurrentTime(audioPlayerContext.currentTime || 0);
              }

              // ⭐ 如果音频对象已存在，清除恢复标志
              if (hasAudioObject && isRestoringAudioRef.current) {
                isRestoringAudioRef.current = false;
              }

              // ⚡ 优化：只在第一次检测到音频对象丢失时重建，避免重复触发
              if (shouldBePlaying && !hasAudioObject) {
                if (!isRestoringAudioRef.current) {
                  isRestoringAudioRef.current = true;

                  // 设置 audioUrl 触发 useEffect 重新创建
                  setAudioUrl(url);
                  setIsPlaying(false);
                  setDuration(firstContent.duration || 0);
                  setCurrentTime(audioPlayerContext.currentTime || 0);
                } else {
                  // 正在恢复中，不要重复触发
                }
                return;
              }

              // 同步播放状态到页面
              setIsPlaying(audioPlayerContext.isPlaying);

              return;
            }

            // ⭐ 新景区或新URL，重置所有状
            setAudioUrl(url);
            setAudioText(text);
            setCurrentTitle(title);
            setCurrentContentIndex(0);
            setIsPlaying(false);
            setDuration(firstContent.duration || 0);
            setCurrentTime(0);
          } else {
            // 没有音频数据时，使用百度TTS生成音频
            const textContent = attraction.description || `欢迎来到${attraction.name || attraction.areaName}！这里风景优美，欢迎您的到来。`;
            setAudioText(textContent);
            setCurrentTitle('景区介绍');
            setCurrentContentIndex(0);
            setIsPlaying(false);
            setDuration(0);
            setCurrentTime(0);

            // 使用百度TTS生成音频文件
            generateTtsAudio(textContent);
          }

          if (audioData.scenicInfo) {
            setScenicInfo(audioData.scenicInfo);
          }
        } else {
          // 后端返回的audioData为null或undefined，使用TTS
          const textContent = attraction.description || `欢迎来到${attraction.name || attraction.areaName}！这里风景优美，欢迎您的到来。`;
          setAudioText(textContent);
          setCurrentTitle('景区介绍');
          setCurrentContentIndex(0);
          setIsPlaying(false);
          setDuration(0);
          setCurrentTime(0);
          generateTtsAudio(textContent);
        }
      } catch (error) {
        // 获取音频数据失败，使用TTS
        const textContent = attraction.description || `欢迎来到${attraction.name || attraction.areaName}！这里风景优美，欢迎您的到来。`;
        setAudioText(textContent);
        setCurrentTitle('景区介绍');
        setCurrentContentIndex(0);
        setIsPlaying(false);
        setDuration(0);
        setCurrentTime(0);
        generateTtsAudio(textContent);
      }
    };

    if (itemId && areaType) {
      fetchAudioData();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [itemId, areaType]);

  // 当audioUrl改变时，自动加载音频（但不自动播放）
  useEffect(() => {
    if (!audioUrl) {
      // ⚡⚡⚡ 重要修复：如果全局有相同景区正在播放，不要停止音频
      // 这种情况通常发生在组件重新挂载但 audioUrl 还没及时恢复时
      const isGlobalPlayingSameAttraction =
        audioPlayerContext.currentAttraction?.id === itemId &&
        (audioPlayerContext.isPlaying || audioPlayerContext.isPaused);

      if (isGlobalPlayingSameAttraction) {
        // 同步播放状态到页面，即使 audioUrl 还没恢复
        setIsPlaying(audioPlayerContext.isPlaying);
        setCurrentTime(audioPlayerContext.currentTime || 0);
        setDuration(audioPlayerContext.duration || 0);

        // 从全局状态恢复文本内容
        if (audioPlayerContext.currentAttraction) {
          setAudioText(audioPlayerContext.currentAttraction.audioText || '');
          setCurrentTitle(
            audioPlayerContext.currentAttraction.audioTitle || '',
          );
        }

        return;
      }

      setIsPlaying(false);
      setCurrentTime(0);
      setDuration(0);
      // ⚡ 优化：只有当真正有音频在播放时才停止
      if (voiceService.currentSound) {
        voiceService.stopAudio();
      }
      lastPlayedAudioUrlRef.current = null;
      return;
    }

    // ⭐⭐⭐ 关键优化：如果是同一个URL，不要重复执行
    if (lastPlayedAudioUrlRef.current === audioUrl) {
      // ⭐⭐⭐ 修复重复播放器问题：即使是同一个 URL，也要同步状态
      const isCurrentAttraction = audioPlayerContext.currentAttraction?.id === itemId;
      if (isCurrentAttraction) {
        // 同步播放状态到页面，但不创建新播放器
        setIsPlaying(audioPlayerContext.isPlaying);
        setCurrentTime(audioPlayerContext.currentTime || 0);
        setDuration(audioPlayerContext.duration || 0);
      }
      return;
    }

    // ⭐⭐⭐ 立即设置 ref，防止后续重复触发
    const previousUrl = lastPlayedAudioUrlRef.current;
    lastPlayedAudioUrlRef.current = audioUrl;

    // 检查全局状态
    const hasGlobalAttraction = audioPlayerContext.currentAttraction !== null;
    const isCurrentAttraction =
      audioPlayerContext.currentAttraction?.id === itemId;
    const hasAudioObject = voiceService.currentSound !== null;


    // 检查是否是 TTS 音频
    const isTtsAudio = audioUrl.includes('/cache/tts_');

    // 情况1：如果全局没有播放状态（用户点击了关闭），从头开始播放
    if (!hasGlobalAttraction) {
      // 不要调用 stopAudio()，因为本来就没有在播放
      setIsPlaying(false);
      setCurrentTime(0);

      // TTS 音频不需要通过 TrackPlayer，已经在 generateTtsAudio 中处理
      if (isTtsAudio) {
        return;
      }

      // ⚡ 立即播放，无延迟
      if (autoPlayRef.current) {
        togglePlayPause();
      }
      return;
    }

    // 情况2：如果是同一个景区（无论音频对象是否存在）
    if (isCurrentAttraction) {

      if (hasAudioObject) {
        // ⭐⭐⭐ 修复重复播放器问题：如枟已经有音频对象且正在播放，不要重新创建
        if (audioPlayerContext.isPlaying) {
          // 正在播放，只同步状态，不重新播放
          setIsPlaying(true);
          return;
        }
        // 如果是暂停状态，自动恢复播放
        if (audioPlayerContext.isPaused && autoPlayRef.current) {
          // ⚡ 立即恢复播放，无延迟
          togglePlayPause();
        } else {
          // 如枟正在播放，同步状态
          setIsPlaying(audioPlayerContext.isPlaying);
        }
      } else {
        // 音频对象不存在
        if (isRestoringAudioRef.current) {
          // 正在恢复音频，从上次的播放位置继续
          const savedTime = audioPlayerContext.currentTime || 0;
          setIsPlaying(false);
          // ⚡ 立即恢复，无延迟（像网易云音乐一样）
          restorePlayback(savedTime); // 标志会在 restorePlayback 完成后自动清除
        } else {
          // 不是恢复状态，等待创建
          setIsPlaying(false);
        }
      }
      return;
    }

    // 情况3：切换到不同的景区，从头开始播放
    setIsPlaying(false);
    setCurrentTime(0);

    // ⚡ 立即播放，无延迟
    if (autoPlayRef.current) {
      togglePlayPause();
    }

    // 注意：离开页面时不停止音频，由用户通过全局控制条控制
    // return () => {
    //   voiceService.stopAudio();
    //   setIsPlaying(false);
    // };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [audioUrl]);

  useEffect(() => {
    if (isPlaying && !progressIntervalRef.current) {
      // 检查是否是 TTS 音频
      const isTtsAudio = audioUrl && audioUrl.includes('/cache/tts_');

      if (isTtsAudio && ttsSoundRef.current) {
        // TTS 音频使用 Sound 对象获取进度
        // ⚡ 优化：减少更新间隔到 200ms，使进度更流畅
        progressIntervalRef.current = setInterval(() => {
          if (ttsSoundRef.current) {
            ttsSoundRef.current.getCurrentTime((currentPos) => {
              const currentSeconds = Math.floor(currentPos);
              setCurrentTime(currentSeconds);

              // ⚡ 实时获取准确时长
              const actualDuration = ttsSoundRef.current.getDuration();
              if (actualDuration > 0 && Math.abs(actualDuration - duration) > 0.5) {
                setDuration(Math.floor(actualDuration));
              }

              // 同步到全局播放状态
              audioPlayerContext.updateProgress(currentSeconds, actualDuration > 0 ? actualDuration : duration);

              // ⚡⚡⚡ TTS预加载：剩余12秒时开始预加载下一个内容
              const timeRemaining = duration - currentPos;
              
              // 调试日志：每10秒输出一次
              if (Math.floor(currentPos) % 10 === 0 && Math.floor(currentPos) !== 0) {
              }
              
              if (timeRemaining <= 12 && timeRemaining > 11 && !nextContentPreloadRef.current) {
                preloadNextContent();
              }

              // ⚡⚡⚡ 自动切换：剩余5秒时自动切换到下一个内容
              if (timeRemaining <= 5 && timeRemaining > 4.5 && !isAutoSwitchingRef.current) {
                if (currentContentIndex < contentList.length - 1) {
                  isAutoSwitchingRef.current = true;
                  handleNext();
                } else {
                }
              }

              // 检查是否播放完成
              if (duration > 0 && currentPos >= duration - 0.1) {
                clearInterval(progressIntervalRef.current);
                progressIntervalRef.current = null;
                setIsPlaying(false);
                setCurrentTime(duration);
                
                // 播放完成后也切换
                if (!isAutoSwitchingRef.current && currentContentIndex < contentList.length - 1) {
                  isAutoSwitchingRef.current = true;
                  setTimeout(() => handleNext(), 500);
                }
              }
            });
          } else {
            clearInterval(progressIntervalRef.current);
            progressIntervalRef.current = null;
          }
        }, 200); // ⚡ 优化：从 500ms 改为 200ms
      } else if (isTtsAudio && !ttsSoundRef.current) {
      } else {
        // 普通音频使用 voiceService
        // ⚡ 优化：立即尝试获取时长
        const audioDuration = voiceService.getDuration();
        if (audioDuration > 0 && duration === 0) {
          setDuration(Math.floor(audioDuration));
        }

        // ⚡ 优化：减少更新间隔到 200ms，使进度更流畅
        progressIntervalRef.current = setInterval(() => {
          voiceService.getCurrentTime((currentPos) => {
            const currentSeconds = Math.floor(currentPos);
            setCurrentTime(currentSeconds);

            // ⚡ 实时获取并更新准确时长
            const totalDuration = voiceService.getDuration();
            if (totalDuration > 0 && Math.abs(totalDuration - duration) > 0.5) {
              setDuration(Math.floor(totalDuration));
            }
            
            // 同步到全局播放状态
            audioPlayerContext.updateProgress(currentSeconds, totalDuration > 0 ? totalDuration : duration);

            // ⚡⚡⚡ TTS预加载：剩余12秒时开始预加载下一个内容
            const timeRemaining = totalDuration - currentPos;
            
            // 调试日志：每10秒输出一次
            if (Math.floor(currentPos) % 10 === 0 && Math.floor(currentPos) !== 0) {
            }
            
            if (timeRemaining <= 12 && timeRemaining > 11 && !nextContentPreloadRef.current) {
              preloadNextContent();
            }

            // ⚡⚡⚡ 自动切换：剩余5秒时自动切换到下一个内容
            if (timeRemaining <= 5 && timeRemaining > 4.5 && !isAutoSwitchingRef.current) {
              if (currentContentIndex < contentList.length - 1) {
                isAutoSwitchingRef.current = true;
                handleNext();
              } else {
              }
            }

            // 检查是否播放完成
            if (totalDuration > 0 && currentPos >= totalDuration - 0.1) {
              clearInterval(progressIntervalRef.current);
              progressIntervalRef.current = null;
              setIsPlaying(false);
              setCurrentTime(Math.floor(totalDuration));
              
              // 播放完成后也切换
              if (!isAutoSwitchingRef.current && currentContentIndex < contentList.length - 1) {
                isAutoSwitchingRef.current = true;
                setTimeout(() => handleNext(), 500);
              }
            }
          });
        }, 200); // ⚡ 优化：从 500ms 改为 200ms
      }
    } else if (!isPlaying && progressIntervalRef.current) {
      clearInterval(progressIntervalRef.current);
      progressIntervalRef.current = null;
    }

    return () => {
      if (progressIntervalRef.current && !isPlaying) {
        clearInterval(progressIntervalRef.current);
        progressIntervalRef.current = null;
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isPlaying, duration, audioUrl, audioPlayerContext, currentContentIndex, contentList.length]);

  // 获取景区下的景点列表（仅当areaType为1时）
  useEffect(() => {
    const fetchSpotsList = async () => {
      if (areaType !== 1) {
        return; // 只有景区才需要获取景点列表
      }

      try {
        setLoadingSpots(true);
        const response = await locationAPI.getScenicAreaAttractions(
          itemId,
          1,
          100,
        );
        const spotsData =
          response?.data?.data?.list || response?.data?.list || [];
        setSpotsList(spotsData);
      } catch {
        setSpotsList([]);
      } finally {
        setLoadingSpots(false);
      }
    };

    if (itemId && areaType) {
      fetchSpotsList();
    }
  }, [itemId, areaType]);

  // 初始化音频播放器
  useEffect(() => {
    setCurrentTime(0);
    setDuration(0);
    return () => {
      if (spinAnimationRef.current) {
        spinAnimationRef.current.stop();
        spinAnimationRef.current = null;
      }
    };
  }, [audioUrl]);

  // 根据播放状态和歌词显示状态控制旋转动画
  useEffect(() => {
    // 检查是否应该播放动画：本地播放或全局播放同一景区
    // 使用更可靠的判断逻辑，确保进入页面时能正确启动
    const globalIsPlaying =
      audioPlayerContext.currentAttraction?.id === itemId &&
      audioPlayerContext.isPlaying;
    const localIsPlaying = isPlaying;
    const shouldAnimate = (localIsPlaying || globalIsPlaying) && !showLyrics;

    if (shouldAnimate) {
      // 延迟一小段时间确保状态已同步（解决进入页面时动画不启动的问题）
      const timer = setTimeout(() => {
        // 先停止之前的动画
        if (spinAnimationRef.current) {
          spinAnimationRef.current.stop();
        }

        // 重新创建动画（从当前角度继续）
        spinAnimationRef.current = Animated.loop(
          Animated.timing(rotateValue, {
            toValue: rotateValue._value + 1, // 从当前值继续旋转
            duration: 5000, // 5秒转一圈
            useNativeDriver: true,
            easing: Easing.linear,
          }),
        );

        spinAnimationRef.current.start();
      }, 100); // 延迟100ms确保状态同步

      return () => {
        clearTimeout(timer);
        if (spinAnimationRef.current) {
          spinAnimationRef.current.stop();
        }
      };
    } else {
      // 暂停时或显示歌词时停止动画
      if (spinAnimationRef.current) {
        spinAnimationRef.current.stop();
        spinAnimationRef.current = null;
      }
    }

    return () => {
      // 清理函数
      if (spinAnimationRef.current) {
        spinAnimationRef.current.stop();
      }
    };
  }, [
    isPlaying,
    showLyrics,
    audioPlayerContext.isPlaying,
    audioPlayerContext.currentAttraction?.id,
    itemId,
    rotateValue,
  ]); // 增加 rotateValue 依赖

  // 根据播放进度自动滚动歌词
  useEffect(() => {
    if (!showLyrics && lyricsScrollRef.current && audioText && duration > 0) {
      // 假设文字内容总高度约为文字长度的一半（根据字体大小和行高估算）
      const estimatedTextHeight = audioText.length * 0.35; // 每个字符大约占0.35像素高度
      const scrollableHeight = Math.max(0, estimatedTextHeight - 50); // 减去容器高度

      // 根据播放进度计算滚动位置
      const progress = currentTime / duration;
      const scrollPosition = scrollableHeight * progress;

      // 滚动到对应位置
      lyricsScrollRef.current?.scrollTo({
        y: scrollPosition,
        animated: true,
      });
    }
  }, [currentTime, duration, showLyrics, audioText]);

  // 播放完成后自动播放下一曲
  /**
   * 使用百度TTS生成音频文件
   * @param {string} text - 要转换的文本
   */
  const generateTtsAudio = useCallback(async (text) => {
    if (!text || text.trim().length === 0) {
      return;
    }

    try {
      setIsTtsGenerating(true);

      // 使用智能策略：优先分段合成（快速）
      const textLength = text.length;
      let audioData;

      const ttsOptions = {
        voiceName: '4',
        speed: '5',
        volume: '9',
        pitch: '5',
      };

      if (textLength > 510) {
        try {
          // 🌊 使用流式播放：第一段合成完立即播放，无需等待
          await baiduTtsService.synthesizeInSegmentsStreaming(text, ttsOptions);

          // 流式TTS播放成功，设置状态并启动进度追踪
          setIsTtsGenerating(false);
          setAudioUrl('/cache/tts_streaming'); // 特殊标识，表示流式TTS正在播放
          setAudioText(text);
          setCurrentTitle(`${attraction.name || attraction.areaName} - 语音讲解`);
          setIsPlaying(true);

          // 更新全局播放状态
          audioPlayerContext.play(
            { ...attraction, areaType },
            '/cache/tts_streaming',
            `${attraction.name || attraction.areaName} - 语音讲解`,
            text,
          );

          // 启动进度追踪
          if (progressIntervalRef.current) {
            clearInterval(progressIntervalRef.current);
          }
          // ⚡ 优化：使用 200ms 间隔，进度更流畅
          progressIntervalRef.current = setInterval(() => {
            baiduTtsService.getCurrentTime((currentPos) => {
              const currentSeconds = Math.floor(currentPos);
              setCurrentTime(currentSeconds);
              const dur = baiduTtsService.getDuration();
              if (dur > 0) {
                // ⚡ 实时更新时长
                if (Math.abs(dur - duration) > 0.5) {
                  setDuration(Math.floor(dur));
                }
                audioPlayerContext.updateProgress(currentSeconds, dur);
              }
            });
          }, 200);

          return;

        } catch (error) {
          console.warn('⚠️ 流式合成失败，降级使用长文本API:', error.message);
          // 降级：使用长文本API
          audioData = await baiduTtsService.synthesizeLongText(text, ttsOptions);
        }
      } else {
        audioData = await baiduTtsService.synthesize(text, ttsOptions);
      }

      // 检查返回的数据是否是有效的音频数据
      if (!audioData || audioData.byteLength < 1000) {
        // 数据太小，可能是错误信息
        console.error('❌ 百度TTS返回数据异常，大小:', audioData?.byteLength);

        // 尝试解析错误信息
        try {
          const uint8Array = new Uint8Array(audioData);
          // 直接打印字节数组
          const bytes = Array.from(uint8Array);
          console.error('原始字节数组:', bytes);

          // 尝试解析为JSON
          const decoder = new TextDecoder('utf-8');
          const errorText = decoder.decode(uint8Array);
          console.error('解析为文本:', errorText);

          // 尝试解析为JSON对象
          try {
            const errorJson = JSON.parse(errorText);
            console.error('百度TTS错误:', errorJson);
          } catch (jsonErr) {
            console.error('不是JSON格式');
          }
        } catch (e) {
          console.error('无法解析错误信息:', e);
        }

        throw new Error('百度TTS返回数据异常，可能是API配置错误或网络问题');
      }

      // 将ArrayBuffer转换为Base64
      const uint8Array = new Uint8Array(audioData);
      let binaryString = '';
      for (let i = 0; i < uint8Array.length; i++) {
        binaryString += String.fromCharCode(uint8Array[i]);
      }
      const base64Audio = btoa(binaryString);

      // 保存到本地缓存
      const fileName = `tts_${itemId}_${Date.now()}.mp3`;
      const audioPath = `${RNFS.CachesDirectoryPath}/${fileName}`;
      await RNFS.writeFile(audioPath, base64Audio, 'base64');

      // 验证文件是否存在
      const fileExists = await RNFS.exists(audioPath);

      if (!fileExists) {
        console.error('❌ 文件不存在!');
        setIsTtsGenerating(false);
        setIsPlaying(false);
        return;
      }

      // 获取文件信息
      const fileInfo = await RNFS.stat(audioPath);

      // 等待100ms确保文件写入完成
      await new Promise(resolve => setTimeout(resolve, 100));

      setIsTtsGenerating(false);

      // ⚠️ TrackPlayer 2.x 有 resolveAssetSource bug，TTS 音频直接使用 Sound 播放

      // 设置状态
      setAudioUrl(audioPath);
      setAudioText(text);
      setCurrentTitle(`${attraction.name || attraction.areaName} - 语音讲解`);
      setIsPlaying(true);

      // 设置音频类别
      Sound.setCategory('Playback');

      // 使用 Sound 直接播放
      const sound = new Sound(audioPath, '', (error) => {
        if (error) {
          console.error('❌ 加载 TTS 音频失败:', error);
          setIsPlaying(false);

          // 后备方案
          baiduTtsService.speak(text, {
            voiceName: '4',
            speed: '5',
            volume: '9',
            pitch: '5',
          }).then(() => {
            setIsPlaying(false);
          }).catch(err => {
            setIsPlaying(false);
          });
          return;
        }

        const duration = sound.getDuration();
        setDuration(duration);

        // 保存 sound 对象以便后续控制
        ttsSoundRef.current = sound;

        // 更新全局播放状态
        audioPlayerContext.play(
          { ...attraction, areaType },
          audioPath,
          `${attraction.name || attraction.areaName} - 语音讲解`,
          text,
        );

        // 立即启动进度追踪
        if (progressIntervalRef.current) {
          clearInterval(progressIntervalRef.current);
        }
        // ⚡ 优化：使用 200ms 间隔，进度更流畅
        progressIntervalRef.current = setInterval(() => {
          if (ttsSoundRef.current) {
            ttsSoundRef.current.getCurrentTime((currentPos) => {
              const currentSeconds = Math.floor(currentPos);
              setCurrentTime(currentSeconds);
              // ⚡ 实时更新时长
              const actualDuration = ttsSoundRef.current.getDuration();
              if (actualDuration > 0 && Math.abs(actualDuration - duration) > 0.5) {
                setDuration(Math.floor(actualDuration));
              }
              audioPlayerContext.updateProgress(currentSeconds, actualDuration > 0 ? actualDuration : duration);
            });
          }
        }, 200);

        // 开始播放
        sound.play((success) => {
          setIsPlaying(false);
          sound.release();
          ttsSoundRef.current = null;

          // 清理进度定时器
          if (progressIntervalRef.current) {
            clearInterval(progressIntervalRef.current);
            progressIntervalRef.current = null;
          }

          // TTS播放完成，自动播放下一曲
          if (contentList.length > 0 && currentContentIndex < contentList.length - 1) {
            const nextIndex = currentContentIndex + 1;
            const nextContent = contentList[nextIndex];
            const nextTitle = nextContent.title || nextContent.name || `第 ${nextIndex + 1} 段`;
            const nextUrl = nextContent.audioUrl || nextContent.audio || nextContent.url;
            const nextText = nextContent.text || nextContent.description || nextContent.content;

            setCurrentContentIndex(nextIndex);
            setCurrentTitle(nextTitle);
            setCurrentTime(0);
            setShowLyrics(false);

            if (!nextUrl && nextText) {
              setDuration(0);
              generateTtsAudio(nextText);
            } else {
              setAudioUrl(nextUrl);
              setAudioText(nextText);
              setDuration(nextContent.duration || 0);
            }
          } else {
            // 已经是最后一曲，停止播放
            audioPlayerContext.stop();
          }
        });
      });
    } catch (error) {
      console.error('❌ TTS生成失败:', error);
      setIsTtsGenerating(false);
      setIsPlaying(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [itemId, attraction, areaType, audioPlayerContext, contentList, currentContentIndex]);

  // ⚡⚡⚡ 预加载下一个内容的TTS音频
  const preloadNextContent = useCallback(async () => {
    if (currentContentIndex >= contentList.length - 1) {
      return; // 已是最后一个
    }

    const nextIndex = currentContentIndex + 1;
    const nextContent = contentList[nextIndex];
    const nextUrl = nextContent.audioUrl || nextContent.audio || nextContent.url;
    const nextText = nextContent.text || nextContent.description || nextContent.content;

    // 只预加载TTS内容（没有音频URL但有文本）
    if (!nextUrl && nextText) {
      try {
        // 预加载TTS音频
        const audioData = await baiduTtsService.synthesize(nextText, {
          voiceName: '4',
          speed: '5',
          volume: '9',
          pitch: '5',
        });

        // 将ArrayBuffer转换为Base64
        const uint8Array = new Uint8Array(audioData);
        let binaryString = '';
        for (let i = 0; i < uint8Array.length; i++) {
          binaryString += String.fromCharCode(uint8Array[i]);
        }
        const base64Audio = btoa(binaryString);

        // 保存到本地缓存
        const fileName = `tts_${itemId}_next_${Date.now()}.mp3`;
        const audioPath = `${RNFS.CachesDirectoryPath}/${fileName}`;
        await RNFS.writeFile(audioPath, base64Audio, 'base64');

        // 保存预加载数据
        nextContentPreloadRef.current = {
          index: nextIndex,
          audioPath,
          text: nextText,
          title: nextContent.title || nextContent.name || `第 ${nextIndex + 1} 段`,
        };

      } catch (error) {
        console.error('[AttractionDetail] TTS预加载失败:', error);
        nextContentPreloadRef.current = null;
      }
    }
  }, [currentContentIndex, contentList, itemId]);

  const handlePlayComplete = useCallback(() => {
    // 如果有下一曲，自动播放
    if (
      contentList.length > 0 &&
      currentContentIndex < contentList.length - 1
    ) {
      const nextIndex = currentContentIndex + 1;
      const nextContent = contentList[nextIndex];
      const title =
        nextContent.title || nextContent.name || `第 ${nextIndex + 1} 段`;
      const nextUrl =
        nextContent.audioUrl || nextContent.audio || nextContent.url;

      if (nextUrl) {
        setCurrentContentIndex(nextIndex);
        setAudioUrl(nextUrl);
        setAudioText(
          nextContent.text || nextContent.description || nextContent.content,
        );
        setCurrentTitle(title);
        setCurrentTime(0);
        setShowLyrics(false);
        setDuration(nextContent.duration || 0);
      } else {
        // 下一曲没有音频，停止播放
        setIsPlaying(false);
        audioPlayerContext.stop(); // 更新全局状态
      }
    } else {
      // 已经是最后一曲，停止播放
      setIsPlaying(false);
      audioPlayerContext.stop(); // 更新全局状态
    }
  }, [contentList, currentContentIndex, audioPlayerContext]);

  const togglePlayPause = useCallback(() => {
    if (!audioUrl) {
      return;
    }

    // 检查是否是TTS生成的音频（本地文件）
    const isTtsAudio = audioUrl.includes('/cache/tts_');

    if (isPlaying) {
      // 暂停播放
      if (isTtsAudio) {
        // TTS音频（单文件或流式）
        if (ttsSoundRef.current) {
          ttsSoundRef.current.pause();
        } else {
          // 流式TTS使用baiduTtsService
          baiduTtsService.pause();
        }
      } else {
        voiceService.pauseAudio();
      }
      setIsPlaying(false);
      audioPlayerContext.pause(); // 更新全局状态
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
        progressIntervalRef.current = null;
      }
    } else {
      // 恢复或开始播放
      setIsBuffering(true);

      // TTS 音频的恢复逻辑
      if (isTtsAudio) {
        if (ttsSoundRef.current) {
          // 单文件TTS
          ttsSoundRef.current.play((success) => {
            if (success) {
            } else {
              setIsPlaying(false);
            }
          });

          // 重新启动进度追踪
          if (progressIntervalRef.current) {
            clearInterval(progressIntervalRef.current);
          }
          // ⚡ 优化：使用 200ms 间隔
          progressIntervalRef.current = setInterval(() => {
            if (ttsSoundRef.current) {
              ttsSoundRef.current.getCurrentTime((currentPos) => {
                const currentSeconds = Math.floor(currentPos);
                setCurrentTime(currentSeconds);
                // ⚡ 实时更新时长
                const actualDuration = ttsSoundRef.current.getDuration();
                if (actualDuration > 0 && Math.abs(actualDuration - duration) > 0.5) {
                  setDuration(Math.floor(actualDuration));
                }
                audioPlayerContext.updateProgress(currentSeconds, actualDuration > 0 ? actualDuration : duration);
              });
            }
          }, 200);
        } else {
          // 流式TTS
          baiduTtsService.resume();

          // 重新启动进度追踪
          if (progressIntervalRef.current) {
            clearInterval(progressIntervalRef.current);
          }
          // ⚡ 优化：使用 200ms 间隔
          progressIntervalRef.current = setInterval(() => {
            baiduTtsService.getCurrentTime((currentPos) => {
              const currentSeconds = Math.floor(currentPos);
              setCurrentTime(currentSeconds);
              const dur = baiduTtsService.getDuration();
              // ⚡ 实时更新时长
              if (dur > 0 && Math.abs(dur - duration) > 0.5) {
                setDuration(Math.floor(dur));
              }
              audioPlayerContext.updateProgress(currentSeconds, dur > 0 ? dur : duration);
            });
          }, 200);
        }

        setIsPlaying(true);
        setIsBuffering(false);
        audioPlayerContext.resume(); // 更新全局状态
        return;
      }

      // 如果有currentSound，说明只是暂停了，可以恢复
      if (voiceService.currentSound) {
        voiceService.resumeAudio(
          (error) => {
            setIsBuffering(false);
            if (error) {
              // 恢复失败，尝试重新播放
              // 通知栏元数据：景区名作为主标题，音频名作为副标题
              const metadata = {
                title: attraction?.name || attraction?.areaName || '景区音频',
                artist: currentTitle || '景区介绍',
                album: '山猫导游',
                duration: duration || 0,
              };

              voiceService.playAudio(
                audioUrl,
                err => {
                  if (err) {
                    setIsPlaying(false);
                    return;
                  }
                  setIsPlaying(true);
                  // 确保传递 areaType，用于从全局播放器重新进入
                  audioPlayerContext.play(
                    { ...attraction, areaType },
                    audioUrl,
                    currentTitle,
                    audioText,
                  );
                },
                handlePlayComplete,
                metadata,
              );
            } else {
              setIsPlaying(true);
              // 确保传递 areaType，用于从全局播放器重新进入
              audioPlayerContext.play(
                { ...attraction, areaType },
                audioUrl,
                currentTitle,
                audioText,
              );
            }
          }, handlePlayComplete);
      } else {
        // 没有currentSound，需要重新加载播放
        // 通知栏元数据：景区名作为主标题，音频名作为副标题
        const metadata = {
          title: attraction?.name || attraction?.areaName || '景区音频',
          artist: currentTitle || '景区介绍',
          album: '山猫导游',
          duration: duration || 0,
        };

        voiceService.playAudio(
          audioUrl,
          error => {
            setIsBuffering(false);
            if (error) {
              setIsPlaying(false);
              return;
            }
            setIsPlaying(true);
            // 确保传递 areaType，用于从全局播放器重新进入
            audioPlayerContext.play(
              { ...attraction, areaType },
              audioUrl,
              currentTitle,
              audioText,
            );
          },
          handlePlayComplete,
          metadata,
        );
      }
    }
  }, [
    audioUrl,
    isPlaying,
    currentTitle,
    audioText,
    attraction,
    duration,
    handlePlayComplete,
    audioPlayerContext,
  ]);

  /**
   * 恢复播放 - 从之前的位置继续播放（音频对象丢失后重建）
   * 🎵 优化：无延迟，像网易云音乐一样流畅
   * ⚡ 恢复标志由 fetchAudioData 检测到音频对象存在后自动清除
   */
  const restorePlayback = useCallback(
    async savedTime => {
      if (!audioUrl) {
        isRestoringAudioRef.current = false; // 清除标志
        return;
      }

      // ⚡ 优化：先更新UI状态，让用户立即看到响应
      setIsPlaying(true);
      // 确保传递 areaType，用于从全局播放器重新进入
      audioPlayerContext.play(
        { ...attraction, areaType },
        audioUrl,
        currentTitle,
        audioText,
      );
      setIsBuffering(true);

      // 准备 metadata
      // 通知栏元数据：景区名作为主标题，音频名作为副标题
      const metadata = {
        title: attraction?.name || attraction?.areaName || '景区音频',
        artist: currentTitle || '景区介绍',
        album: '山猫导游',
        duration: duration || 0,
      };

      // 重新加载音频（后台进行）
      await voiceService.playAudio(
        audioUrl,
        error => {
          setIsBuffering(false);

          if (error) {
            setIsPlaying(false);
            audioPlayerContext.pause();
            // 失败后立即清除标志
            isRestoringAudioRef.current = false;
            return;
          }

          // ⚡ 立即跳转到之前的播放位置（无延迟）
          if (savedTime > 0) {
            voiceService.setCurrentTime(savedTime);
            setCurrentTime(savedTime);
          }

          // 标志会在下次 fetchAudioData 检测到音频对象存在时自动清除
        },
        handlePlayComplete,
        metadata,
      );
    },
    [
      audioUrl,
      currentTitle,
      audioText,
      attraction,
      duration,
      handlePlayComplete,
      audioPlayerContext,
    ],
  );

  const handlePlayPause = () => {
    buttonPressedRef.current = true;
    togglePlayPause();
  };

  const handleProgressPress = useCallback(
    event => {
      if (!audioUrl || duration === 0) return;

      const { locationX } = event.nativeEvent;
      // 获取进度条的实际宽度
      event.target.measure((x, y, width) => {
        const percentage = Math.max(0, Math.min(1, locationX / width));
        const newTime = Math.floor(duration * percentage);

        // 检查是否是TTS音频
        const isTtsAudio = audioUrl.includes('/cache/tts_');

        if (isTtsAudio) {
          if (ttsSoundRef.current) {
            // 单文件TTS
            ttsSoundRef.current.setCurrentTime(newTime);
          } else {
            // 流式TTS
            baiduTtsService.setCurrentTime(newTime);
          }
          setCurrentTime(newTime);
          audioPlayerContext.updateProgress(newTime, duration);
        } else {
          // 普通音频使用 voiceService
          setCurrentTime(newTime);
          voiceService.setCurrentTime(newTime);
          audioPlayerContext.updateProgress(newTime, duration);
        }
      });
    },
    [audioUrl, duration, audioPlayerContext],
  );

  const handlePrevious = useCallback(async () => {
    if (contentList.length > 0) {
      // 重置自动切换标志
      isAutoSwitchingRef.current = false;
      // 清除预加载数据
      nextContentPreloadRef.current = null;

      const newIndex =
        currentContentIndex > 0
          ? currentContentIndex - 1
          : contentList.length - 1;
      const newContent = contentList[newIndex];
      const title = newContent.title || newContent.name || `第 ${newIndex + 1} 段`;
      const url = newContent.audioUrl || newContent.audio || newContent.url;
      const text = newContent.text || newContent.description || newContent.content;

      // 先停止当前播放
      if (ttsSoundRef.current) {
        try {
          ttsSoundRef.current.stop();
          ttsSoundRef.current.release();
        } catch (e) {
        }
        ttsSoundRef.current = null;
      }
      // 停止流式TTS
      await baiduTtsService.stop();
      // 停止普通音频
      if (isPlaying) {
        voiceService.stopAudio();
      }
      setIsPlaying(false);
      audioPlayerContext.pause();
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
        progressIntervalRef.current = null;
      }

      setCurrentContentIndex(newIndex);
      setAudioText(text);
      setCurrentTitle(title);
      setCurrentTime(0);
      setShowLyrics(false);

      // 判断是否需要使用 TTS
      if (!url && text) {
        setDuration(0);
        generateTtsAudio(text);
      } else {
        setAudioUrl(url);
        setDuration(newContent.duration || 0);
      }
    }
  }, [contentList, currentContentIndex, isPlaying, audioPlayerContext, generateTtsAudio]);

  const handleNext = useCallback(async () => {
    if (contentList.length > 0) {
      // 重置自动切换标志，允许下次自动切换
      isAutoSwitchingRef.current = false;

      const newIndex =
        currentContentIndex < contentList.length - 1
          ? currentContentIndex + 1
          : 0;
      const newContent = contentList[newIndex];
      const title = newContent.title || newContent.name || `第 ${newIndex + 1} 段`;
      const url = newContent.audioUrl || newContent.audio || newContent.url;
      const text = newContent.text || newContent.description || newContent.content;

      // 检查是否有预加载数据
      const hasPreloaded = nextContentPreloadRef.current && nextContentPreloadRef.current.index === newIndex;

      // 先停止当前播放
      if (ttsSoundRef.current) {
        try {
          ttsSoundRef.current.stop();
          ttsSoundRef.current.release();
        } catch (e) {
        }
        ttsSoundRef.current = null;
      }
      // 停止流式TTS
      await baiduTtsService.stop();
      // 停止普通音频
      if (isPlaying) {
        voiceService.stopAudio();
      }
      setIsPlaying(false);
      audioPlayerContext.pause();
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
        progressIntervalRef.current = null;
      }

      setCurrentContentIndex(newIndex);
      setAudioText(text);
      setCurrentTitle(title);
      setCurrentTime(0);
      setShowLyrics(false);

      // 判断是否需要使用 TTS
      if (!url && text) {
        if (hasPreloaded) {
          // 使用预加载的音频
          const preloadedPath = nextContentPreloadRef.current.audioPath;
          setAudioUrl(preloadedPath);
          
          // 清除预加载数据
          nextContentPreloadRef.current = null;
          
          // 直接播放预加载的音频
          setDuration(0);
          setIsPlaying(true);
          Sound.setCategory('Playback');
          const sound = new Sound(preloadedPath, '', (error) => {
            if (error) {
              console.error('⚠️ 预加载音频加载失败，重新生成');
              generateTtsAudio(text);
              return;
            }
            const dur = sound.getDuration();
            setDuration(dur);
            ttsSoundRef.current = sound;
            audioPlayerContext.play(
              { ...attraction, areaType },
              preloadedPath,
              title,
              text,
            );
            sound.play(() => {
              setIsPlaying(false);
              sound.release();
              ttsSoundRef.current = null;
            });
          });
        } else {
          // 没有预加载，正常生成
          nextContentPreloadRef.current = null;
          setDuration(0);
          generateTtsAudio(text);
        }
      } else {
        // 清除预加载数据
        nextContentPreloadRef.current = null;
        setAudioUrl(url);
        setDuration(newContent.duration || 0);
      }
    }
  }, [contentList, currentContentIndex, isPlaying, audioPlayerContext, generateTtsAudio, attraction, areaType]);

  const handleFastForward = async () => {
    if (!audioUrl) {
      return;
    }

    // 检查是否是TTS音频
    const isTtsAudio = audioUrl.includes('/cache/tts_');
    if (isTtsAudio) {
      const newTime = Math.min(currentTime + CONSTANTS.FAST_SEEK_DURATION, duration);
      if (ttsSoundRef.current) {
        // 单文件TTS
        ttsSoundRef.current.setCurrentTime(newTime);
      } else {
        // 流式TTS
        baiduTtsService.setCurrentTime(newTime);
      }
      setCurrentTime(newTime);
      audioPlayerContext.updateProgress(newTime, duration);
      return;
    }

    try {
      // 获取实际的播放位置（更准确）
      const actualPosition = await trackPlayerService.getPosition();
      const actualDuration =
        (await trackPlayerService.getDuration()) || duration;
      const newTime = Math.min(
        actualPosition + CONSTANTS.FAST_SEEK_DURATION,
        actualDuration,
      );

      // 使用 TrackPlayer 的 seekTo 方法
      await trackPlayerService.seekTo(newTime);

      // 更新本地和全局状态
      setCurrentTime(newTime);
      if (actualDuration > 0) {
        setDuration(actualDuration);
      }
      audioPlayerContext.updateProgress(newTime, actualDuration);
    } catch (error) {
      // 降级方案：使用本地状态和 voiceService
      try {
        const fallbackTime = Math.min(
          currentTime + CONSTANTS.FAST_SEEK_DURATION,
          duration,
        );
        await voiceService.setCurrentTime(fallbackTime);
        setCurrentTime(fallbackTime);
        audioPlayerContext.updateProgress(fallbackTime, duration);
      } catch (err) {
      }
    }
  };

  const handleFastBackward = async () => {
    if (!audioUrl) {
      return;
    }

    // 检查是否是TTS音频
    const isTtsAudio = audioUrl.includes('/cache/tts_');
    if (isTtsAudio) {
      const newTime = Math.max(0, currentTime - CONSTANTS.FAST_SEEK_DURATION);
      if (ttsSoundRef.current) {
        // 单文件TTS
        ttsSoundRef.current.setCurrentTime(newTime);
      } else {
        // 流式TTS
        baiduTtsService.setCurrentTime(newTime);
      }
      setCurrentTime(newTime);
      audioPlayerContext.updateProgress(newTime, duration);
      return;
    }

    try {
      // 获取实际的播放位置（更准确）
      const actualPosition = await trackPlayerService.getPosition();
      const newTime = Math.max(
        0,
        actualPosition - CONSTANTS.FAST_SEEK_DURATION,
      );

      // 使用 TrackPlayer 的 seekTo 方法
      await trackPlayerService.seekTo(newTime);

      // 更新本地和全局状态
      setCurrentTime(newTime);
      audioPlayerContext.updateProgress(newTime, duration);
    } catch (error) {
      // 降级方案：使用本地状态和 voiceService
      try {
        const fallbackTime = Math.max(
          0,
          currentTime - CONSTANTS.FAST_SEEK_DURATION,
        );
        await voiceService.setCurrentTime(fallbackTime);
        setCurrentTime(fallbackTime);
        audioPlayerContext.updateProgress(fallbackTime, duration);
      } catch (err) {
      }
    }
  };

  const _handleSeek = position => {
    const clampedPosition = Math.max(0, Math.min(duration || 0, position));
    setCurrentTime(clampedPosition);
    voiceService.setCurrentTime(clampedPosition);
  };

  // 处理景点列表项点击
  const handleSpotPress = useCallback(
    spot => {
      // 导航到该景点的播放页
      navigation.push('AttractionDetail', {
        attraction: spot,
        itemType: 'scenicSpot',
        itemId: spot.id,
        areaType: 2, // 景点的areaType为2
      });
    },
    [navigation],
  );

  const formatTime = useCallback(seconds => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins.toString().padStart(2, '0')}:${secs
      .toString()
      .padStart(2, '0')}`;
  }, []);

  const rootViewProps = panResponder?.current
    ? panResponder.current.panHandlers
    : {};

  return (
    <View style={styles.container} {...rootViewProps}>
      {/* 全屏状态栏配置 - 完全隐藏状态栏 */}
      <StatusBar
        barStyle="light-content"
        backgroundColor="transparent"
        translucent={true}
        hidden={true}
        animated={true}
      />

      {/* 背景图片 - 使用后端返回的coverImage */}
      {getValidImageUri(attraction.coverImage, attraction.image) && (
        <Image
          source={{
            uri: getValidImageUri(attraction.coverImage, attraction.image),
          }}
          style={styles.backgroundImage}
          pointerEvents="none"
        />
      )}

      {/* 模糊遮罩 */}
      <View style={styles.blurOverlay} pointerEvents="none" />

      {/* 渐变遮罩 */}
      <View style={styles.gradientOverlay} pointerEvents="none" />

      {/* 全屏歌词显示 - 覆盖整个屏幕 */}
      {showLyrics && (
        <View style={styles.fullScreenLyricsWrapper}>
          <TouchableOpacity
            style={styles.fullScreenLyricsBackdrop}
            activeOpacity={1}
            onPress={() => setShowLyrics(false)}
          />
          <View style={styles.fullScreenLyricsContainer}>
            <ScrollView
              showsVerticalScrollIndicator={true}
              contentContainerStyle={styles.fullScreenLyricsContent}
            >
              <TouchableOpacity
                activeOpacity={1}
                onPress={() => setShowLyrics(false)}
              >
                <Text style={styles.fullScreenLyricsText}>
                  {audioText || '暂无内容'}
                </Text>
              </TouchableOpacity>
            </ScrollView>
          </View>
        </View>
      )}

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={{ paddingBottom: 50 }}
        showsVerticalScrollIndicator={false}
        scrollEnabled={!showLyrics}
        onScroll={Animated.event(
          [{ nativeEvent: { contentOffset: { y: scrollY } } }],
          { useNativeDriver: false },
        )}
      >
        {/* 播放器区域 */}
        <View style={styles.playerContainer}>
          {/* 音频封面 */}
          {!showLyrics && (
            <View style={styles.albumArtContainer}>
              {/* 封面图片 - 可点击显示文字 */}
              <TouchableOpacity
                style={styles.albumArtImageWrapper}
                onPress={() => {
                  setShowLyrics(true);
                }}
                activeOpacity={0.9}
              >
                {getValidImageUri(attraction.coverImage, attraction.image) ? (
                  <Animated.Image
                    source={{
                      uri: getValidImageUri(
                        attraction.coverImage,
                        attraction.image,
                      ),
                    }}
                    style={[
                      styles.albumArt,
                      {
                        transform: [
                          {
                            rotate: rotateValue.interpolate({
                              inputRange: [0, 1],
                              outputRange: ['0deg', '360deg'],
                            }),
                          },
                        ],
                      },
                    ]}
                  />
                ) : (
                  <View style={[styles.albumArt, styles.albumArtPlaceholder]}>
                    <Icon
                      name="image-outline"
                      size={80}
                      color="rgba(255,255,255,0.3)"
                    />
                  </View>
                )}
              </TouchableOpacity>
              {/* 播放按钮 - 绝对定位在中心，独立控制 */}
              <View style={styles.playButtonWrapper} pointerEvents="box-none">
                <TouchableOpacity
                  style={styles.albumArtPlayButton}
                  onPress={() => {
                    handlePlayPause();
                  }}
                  activeOpacity={0.8}
                  disabled={isTtsGenerating}
                >
                  <View style={(!audioUrl && audioPlayerContext.currentAttraction?.id !== itemId && !isTtsGenerating) ? styles.playButtonInnerDisabled : styles.playButtonInner}>
                    {isTtsGenerating ? (
                      <Icon name="hourglass-outline" size={40} color="#fff" />
                    ) : (!audioUrl && audioPlayerContext.currentAttraction?.id !== itemId) ? (
                      <Icon name="volume-mute" size={40} color="#fff" />
                    ) : isPlaying ||
                      (audioPlayerContext.currentAttraction?.id === itemId &&
                        audioPlayerContext.isPlaying) ? (
                      <Icon name="pause" size={40} color="#fff" />
                    ) : (
                      <Icon name="play" size={40} color="#fff" />
                    )}
                  </View>
                </TouchableOpacity>
              </View>

              {/* TTS生成状态提示 */}
              {isTtsGenerating && (
                <View style={styles.ttsGeneratingHint}>
                  <Text style={styles.ttsGeneratingText}>正在生成语音...</Text>
                </View>
              )}
            </View>
          )}

          {/* 标题显示区域 */}
          {!showLyrics && currentTitle && (
            <View style={styles.titleContainer}>
              <Text style={styles.currentTitle} numberOfLines={2}>
                {currentTitle}
              </Text>
              {contentList.length > 1 && (
                <Text style={styles.contentIndicator}>
                  {currentContentIndex + 1} / {contentList.length}
                </Text>
              )}
            </View>
          )}

          {/* 歌词滚动区域 - 始终显示在红框位置，点击显示全屏文字 */}
          {!showLyrics && (
            <TouchableOpacity
              style={styles.audioInfo}
              onPress={() => setShowLyrics(true)}
              activeOpacity={0.9}
            >
              <ScrollView
                ref={lyricsScrollRef}
                style={styles.miniLyricsContainer}
                showsVerticalScrollIndicator={false}
                scrollEnabled={false}
              >
                <Text style={styles.miniLyricsText}>
                  {audioText || '暂无内容'}
                </Text>
              </ScrollView>
            </TouchableOpacity>
          )}

          {/* 进度条 - 只在显示封面时显示 */}
          {!showLyrics && (
            <View style={styles.progressContainer}>
              <Text style={styles.timeText}>{formatTime(currentTime)}</Text>
              <View style={styles.progressBar}>
                <TouchableOpacity
                  style={styles.progressBarTrack}
                  onPress={handleProgressPress}
                  activeOpacity={0.8}
                >
                  <View
                    style={[
                      styles.progress,
                      {
                        width: `${duration > 0 ? (currentTime / duration) * 100 : 0
                          }%`,
                      },
                    ]}
                  />

                  {/* 进度指示器圆点 */}
                  <View
                    style={[
                      styles.progressThumb,
                      {
                        left: `${duration > 0
                          ? Math.max(
                            0,
                            Math.min(100, (currentTime / duration) * 100),
                          )
                          : 0
                          }%`,
                      },
                    ]}
                  />
                </TouchableOpacity>
              </View>
              <Text style={styles.timeText}>{formatTime(duration)}</Text>
            </View>
          )}

          {/* 控制按钮 - 只在显示封面时显示 */}
          {!showLyrics && (
            <View style={styles.controlsContainer}>
              <TouchableOpacity
                style={styles.controlButton}
                onPress={handlePrevious}
              >
                <Icon name="play-skip-back" size={24} color="#fff" />
              </TouchableOpacity>

              <TouchableOpacity
                style={styles.controlButton}
                onPress={handleFastBackward}
              >
                <Icon name="play-back" size={22} color="#fff" />
              </TouchableOpacity>

              <TouchableOpacity
                style={styles.playButton}
                onPress={handlePlayPause}
              >
                <Icon
                  name={isPlaying ? 'pause-circle' : 'play-circle'}
                  size={46}
                  color="#fff"
                />
              </TouchableOpacity>

              <TouchableOpacity
                style={styles.controlButton}
                onPress={handleFastForward}
              >
                <Icon name="play-forward" size={22} color="#fff" />
              </TouchableOpacity>

              <TouchableOpacity
                style={styles.controlButton}
                onPress={handleNext}
              >
                <Icon name="play-skip-forward" size={24} color="#fff" />
              </TouchableOpacity>
            </View>
          )}
        </View>

        {/* 景区详细信息 */}
        {!showLyrics && (
          <View style={styles.detailInfoSection}>
            <Text style={styles.detailInfoTitle}>景区信息</Text>

            <View style={styles.infoTopRow}>
              <Text style={styles.attractionName}>
                {scenicInfo?.areaName ||
                  attraction.areaName ||
                  attraction.name ||
                  '未知景区'}
              </Text>
              {(scenicInfo?.level || attraction.level) && (
                <View style={styles.levelBadge}>
                  <Text style={styles.levelBadgeText}>
                    {scenicInfo?.level || attraction.level}
                  </Text>
                </View>
              )}
            </View>

            {(scenicInfo?.address || attraction.address) && (
              <Text style={styles.attractionAddress}>
                📍 {scenicInfo?.address || attraction.address}
              </Text>
            )}

            <View style={styles.ratingContainer}>
              {(scenicInfo?.rating || attraction.rating) &&
                parseFloat(scenicInfo?.rating || attraction.rating) > 0 && (
                  <Text style={styles.rating}>
                    ⭐ {scenicInfo?.rating || attraction.rating}
                  </Text>
                )}
              {(attraction.distance || scenicInfo?.distance) && (
                <Text style={styles.distance}>
                  📏 {attraction.distance || scenicInfo?.distance}
                </Text>
              )}
              {Number(
                scenicInfo?.recommendedDuration ||
                attraction.recommendedDuration,
              ) > 0 && (
                  <Text style={styles.duration}>
                    ⏱️{' '}
                    {scenicInfo?.recommendedDuration ||
                      attraction.recommendedDuration}
                    分钟
                  </Text>
                )}
            </View>

            {(scenicInfo?.openingHours || attraction.openingHours) && (
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>🕐 开放时间</Text>
                <Text style={styles.infoText}>
                  {scenicInfo?.openingHours || attraction.openingHours}
                </Text>
              </View>
            )}

            {(scenicInfo?.ticketInfo || attraction.ticketInfo) && (
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>🎫 门票信息</Text>
                <Text style={styles.infoText}>
                  {scenicInfo?.ticketInfo || attraction.ticketInfo}
                </Text>
              </View>
            )}

            {scenicInfo?.addedService && (
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>💡 特色服务</Text>
                <Text style={styles.infoText}>{scenicInfo.addedService}</Text>
              </View>
            )}

            {(scenicInfo?.trafficInfo || attraction.trafficInfo) && (
              <View style={styles.infoRow}>
                <Text style={styles.infoLabel}>🚗 交通信息</Text>
                <Text style={styles.infoText}>
                  {scenicInfo?.trafficInfo || attraction.trafficInfo}
                </Text>
              </View>
            )}
          </View>
        )}

        {/* 景区景点列表 - 仅当areaType为1时显示 */}
        {!showLyrics && areaType === 1 && (
          <View style={styles.spotsListContainer}>
            <Text style={styles.spotsListTitle}>景区内景点</Text>
            {loadingSpots ? (
              <Text style={styles.loadingText}>加载中...</Text>
            ) : spotsList.length > 0 ? (
              spotsList.map((spot, index) => (
                <TouchableOpacity
                  key={spot.id || index}
                  style={styles.spotItem}
                  onPress={() => handleSpotPress(spot)}
                  activeOpacity={0.7}
                >
                  {getValidImageUri(spot.coverImage, spot.image) ? (
                    <Image
                      source={{
                        uri: getValidImageUri(spot.coverImage, spot.image),
                      }}
                      style={styles.spotImage}
                    />
                  ) : (
                    <View
                      style={[styles.spotImage, styles.spotImagePlaceholder]}
                    >
                      <Icon name="image-outline" size={32} color="#999" />
                    </View>
                  )}
                  <View style={styles.spotInfo}>
                    <Text style={styles.spotName} numberOfLines={1}>
                      {spot.name || spot.areaName}
                    </Text>
                    <Text style={styles.spotDescription} numberOfLines={2}>
                      {spot.description ||
                        spot.highlightDescription ||
                        '探索这个美丽的景点'}
                    </Text>
                  </View>
                  <Icon
                    name="chevron-forward"
                    size={20}
                    color="rgba(255,255,255,0.6)"
                  />
                </TouchableOpacity>
              ))
            ) : (
              <Text style={styles.emptyText}>暂无景点信息</Text>
            )}
          </View>
        )}
      </ScrollView>

      {/* 返回按钮 - 放在最后以确保在最上层 */}
      <View
        style={[
          styles.backButtonContainer,
          { top: Platform.OS === 'android' ? 20 : insets.top + 10 },
        ]}
        pointerEvents="box-none"
      >
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => {
            navigation.goBack();
          }}
          activeOpacity={0.7}
        >
          <Icon name="chevron-back" size={28} color="#fff" />
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    height: '100%',
    backgroundColor: 'transparent',
  },
  backButtonContainer: {
    position: 'absolute',
    // top 通过内联样式动态设置，使用 insets.top + 10
    left: 20,
    width: 60,
    height: 60,
    zIndex: 9999, // 超高层级
    elevation: 999,
  },
  backButton: {
    width: 40,
    height: 40,
    borderRadius: RADIUS.xl,
    backgroundColor: COLORS.background.overlay,
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: COLORS.shadow,
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.3,
    shadowRadius: 4,
    elevation: 10,
  },
  backgroundImage: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: width,
    height: Platform.OS === 'android' ? realHeight + 200 : height + 100, // Android使用更大的高度
    resizeMode: 'cover',
    zIndex: -1, // 确保背景在最底层
  },
  blurOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: width,
    height: Platform.OS === 'android' ? realHeight + 200 : height + 100, // Android使用更大的高度
    backgroundColor: 'rgba(0,0,0,0)', // 完全透明，移除所有黑色遮罩
    zIndex: -1, // 确保在背景层
  },
  gradientOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: width,
    height: Platform.OS === 'android' ? realHeight + 200 : height + 100, // Android使用更大的高度
    backgroundColor: 'rgba(0,0,0,0)', // 完全透明，移除所有黑色遮罩
    zIndex: -1, // 确保在背景层
  },
  scrollView: {
    flex: 1,
    backgroundColor: 'transparent',
    zIndex: 1, // 确保内容在前景
  },
  attractionInfo: {
    paddingHorizontal: SPACING.xl,
    paddingTop: Platform.OS === 'android' ? SPACING.xl : 10,
    marginBottom: 30,
  },
  nameRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  attractionName: {
    fontSize: FONT_SIZE.huge,
    fontWeight: FONT_WEIGHT.bold,
    color: COLORS.white,
    flex: 1,
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  levelBadge: {
    backgroundColor: 'rgba(255, 107, 53, 0.9)',
    paddingHorizontal: SPACING.md,
    paddingVertical: 6,
    borderRadius: RADIUS.lg,
    marginLeft: 10,
  },
  levelBadgeText: {
    color: COLORS.white,
    fontSize: FONT_SIZE.md,
    fontWeight: FONT_WEIGHT.semibold,
  },
  attractionAddress: {
    fontSize: 16,
    color: 'rgba(255,255,255,0.9)',
    marginBottom: 12,
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  ratingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  rating: {
    fontSize: FONT_SIZE.lg,
    color: COLORS.primary,
    fontWeight: FONT_WEIGHT.semibold,
    marginRight: SPACING.xl,
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  distance: {
    fontSize: 16,
    color: 'rgba(255,255,255,0.9)',
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  playerContainer: {
    marginHorizontal: SPACING.xl,
    padding: SPACING.xl,
  },
  albumArtContainer: {
    alignSelf: 'center',
    marginBottom: 20,
    position: 'relative',
    width: 280,
    height: 280,
    justifyContent: 'center',
    alignItems: 'center',
  },
  albumArtImageWrapper: {
    width: 200,
    height: 200,
    borderRadius: 100,
  },
  albumArt: {
    width: 200,
    height: 200,
    borderRadius: 100,
    backgroundColor: '#333',
  },
  albumArtPlaceholder: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
  albumArtOverlay: {
    position: 'absolute',
    top: 40,
    left: 40,
    width: 200,
    height: 200,
    borderRadius: 100,
    backgroundColor: 'rgba(0,0,0,0.3)',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 10, // 确保按钮在最上层
  },
  playButtonWrapper: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: 280,
    height: 280,
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 20, // 比封面图片层级高
  },
  albumArtPlayButton: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: 'transparent',
    justifyContent: 'center',
    alignItems: 'center',
  },
  playButtonInnerDisabled: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  playButtonInner: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: 'rgba(255, 107, 53, 0.8)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  ttsGeneratingHint: {
    position: 'absolute',
    bottom: -50,
    alignSelf: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 20,
  },
  ttsGeneratingText: {
    fontSize: 14,
    color: '#fff',
    fontWeight: '500',
  },
  miniLyricsContainer: {
    width: '100%',
    maxHeight: 100,
    marginTop: 10,
  },
  miniLyricsText: {
    fontSize: 15,
    lineHeight: 24,
    color: 'rgba(255,255,255,0.9)',
    textAlign: 'center',
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  fullScreenLyricsWrapper: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 1000,
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
  },
  fullScreenLyricsBackdrop: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'transparent',
  },
  fullScreenLyricsContainer: {
    flex: 1,
    backgroundColor: 'transparent',
  },
  fullScreenLyricsContent: {
    paddingTop: 150,
    paddingBottom: 150,
    paddingHorizontal: 30,
  },
  fullScreenLyricsTitle: {
    fontSize: 22,
    fontWeight: 'bold',
    color: '#fff',
    textAlign: 'center',
    marginBottom: 20,
    paddingVertical: 12,
    paddingHorizontal: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    borderRadius: 12,
    textShadowColor: 'rgba(0, 0, 0, 0.9)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 4,
  },
  fullScreenLyricsText: {
    fontSize: 17,
    lineHeight: 30,
    color: '#fff',
    textAlign: 'justify',
    backgroundColor: 'transparent',
    textShadowColor: 'rgba(0, 0, 0, 0.9)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 4,
  },
  closeHint: {
    paddingVertical: 15,
    paddingHorizontal: 20,
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.6)',
    borderRadius: 20,
    marginTop: 15,
    alignSelf: 'center',
  },
  closeHintText: {
    fontSize: 13,
    color: 'rgba(255,255,255,0.9)',
    textAlign: 'center',
    fontWeight: '500',
  },
  titleContainer: {
    alignItems: 'center',
    marginBottom: 15,
    paddingHorizontal: 20,
  },
  currentTitle: {
    fontSize: 20,
    fontWeight: '700',
    color: '#fff',
    textAlign: 'center',
    marginBottom: 6,
    textShadowColor: 'rgba(0, 0, 0, 0.9)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 4,
  },
  contentIndicator: {
    fontSize: 14,
    color: 'rgba(255,255,255,0.7)',
    fontWeight: '500',
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  audioInfo: {
    alignItems: 'center',
    marginBottom: 20,
  },
  audioTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#fff',
    textAlign: 'center',
    marginBottom: 4,
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  audioAuthor: {
    fontSize: 14,
    color: 'rgba(255,255,255,0.9)',
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  progressContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 20,
  },
  timeText: {
    fontSize: 12,
    color: 'rgba(255,255,255,0.7)',
    minWidth: 40,
  },
  progressBar: {
    flex: 1,
    height: 20,
    marginHorizontal: 10,
    justifyContent: 'center',
    paddingVertical: 8,
  },
  progressBarTrack: {
    height: 4,
    backgroundColor: 'rgba(255,255,255,0.3)',
    borderRadius: 2,
    position: 'relative',
    justifyContent: 'center',
  },
  progress: {
    height: '100%',
    backgroundColor: '#ff6b35',
    borderRadius: 2,
  },
  progressThumb: {
    position: 'absolute',
    width: 12,
    height: 12,
    borderRadius: 6,
    backgroundColor: '#fff',
    borderWidth: 2,
    borderColor: '#ff6b35',
    top: -4,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
    zIndex: 10,
  },
  controlsContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 30,
    paddingHorizontal: 10,
  },
  controlButton: {
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: 'rgba(255,255,255,0.2)',
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 8,
  },
  playButton: {
    width: 70,
    height: 70,
    borderRadius: 35,
    backgroundColor: '#ff6b35',
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 15,
  },
  playPauseButton: {
    width: 70,
    height: 70,
    borderRadius: 35,
    backgroundColor: '#ff6b35',
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 15,
  },
  controlButtonDisabled: {
    width: 50,
    height: 50,
    borderRadius: 25,
    backgroundColor: 'rgba(255,255,255,0.1)',
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 8,
  },
  playPauseButtonDisabled: {
    backgroundColor: 'rgba(255,255,255,0.1)',
  },
  // 景点列表样式
  spotsListContainer: {
    marginHorizontal: 20,
    marginTop: 30,
    marginBottom: 40,
    padding: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    borderRadius: 15,
  },
  spotsListTitle: {
    fontSize: 20,
    fontWeight: '700',
    color: '#fff',
    marginBottom: 15,
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  loadingText: {
    fontSize: 14,
    color: 'rgba(255,255,255,0.7)',
    textAlign: 'center',
    paddingVertical: 20,
  },
  emptyText: {
    fontSize: 14,
    color: 'rgba(255,255,255,0.5)',
    textAlign: 'center',
    paddingVertical: 20,
  },
  spotItem: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: 12,
    padding: 12,
    marginBottom: 12,
  },
  spotImage: {
    width: 60,
    height: 60,
    borderRadius: 8,
    backgroundColor: '#333',
  },
  spotImagePlaceholder: {
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2a2a2a',
  },
  spotInfo: {
    flex: 1,
    marginLeft: 12,
    marginRight: 8,
  },
  spotName: {
    fontSize: 16,
    fontWeight: '600',
    color: '#fff',
    marginBottom: 4,
    textShadowColor: 'rgba(0, 0, 0, 0.8)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
  },
  spotDescription: {
    fontSize: 13,
    color: 'rgba(255,255,255,0.7)',
    lineHeight: 18,
  },
  audioNoticeContainer: {
    alignItems: 'center',
    marginTop: 20,
    padding: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    borderRadius: 15,
  },
  audioNoticeIcon: {
    marginBottom: 10,
  },
  audioNoticeTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 5,
    textAlign: 'center',
  },
  audioNoticeDesc: {
    fontSize: 14,
    color: 'rgba(255,255,255,0.7)',
    textAlign: 'center',
    marginBottom: 15,
  },
  audioTextCard: {
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
    borderRadius: 10,
    padding: 15,
  },
  audioTextScroll: {
    maxHeight: 200,
  },
  audioTextContent: {
    fontSize: 16,
    lineHeight: 24,
    color: 'rgba(255,255,255,0.9)',
    textAlign: 'justify',
  },
  audioPlaceholderBanner: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.4)',
    borderRadius: 15,
    padding: 15,
    marginTop: 20,
  },
  audioPlaceholderIcon: {
    marginRight: 10,
  },
  audioPlaceholderText: {
    fontSize: 14,
    color: 'rgba(255,255,255,0.7)',
  },
  duration: {
    fontSize: 14,
    color: 'rgba(255,255,255,0.9)',
  },
  detailInfoSection: {
    marginTop: 20,
    marginHorizontal: 20,
    padding: 18,
    borderRadius: 14,
    backgroundColor: 'rgba(0, 0, 0, 0.35)',
  },
  detailInfoTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: '#fff',
    marginBottom: 12,
  },
  infoTopRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 6,
  },
  infoRow: {
    marginTop: 12,
    backgroundColor: 'rgba(0,0,0,0.3)',
    padding: 12,
    borderRadius: 8,
  },
  infoLabel: {
    fontSize: 14,
    color: '#fff',
    fontWeight: '600',
    marginBottom: 6,
  },
  infoText: {
    fontSize: 13,
    color: 'rgba(255,255,255,0.85)',
    lineHeight: 20,
  },
});
